from fastapi import FastAPI, HTTPException,APIRouter
from pydantic import BaseModel
from typing import List
import uvicorn

# 创建FastAPI应用
app01 = APIRouter()
# app01 = FastAPI(title="沃林学生信息管理系统")

# 学生信息数据模型
class Student(BaseModel):
    stu_id: str
    stu_c: str
    stu_name: str
    addr: str
    college: str
    major: str
    starttime: str
    endtime: str
    edu: str
    cou_id: str
    age: int
    sex: str


# 模拟数据库 - 存储学生信息
students = [
    {
        "stu_id": "23022801",
        "stu_c": "2302228",
        "stu_name": "鲁大师",
        "addr": "湖南",
        "college": "湖南工学院",
        "major": "应用数学",
        "starttime": "2015-09-01",
        "endtime": "2019-07-01",
        "edu": "本科",
        "cou_id": "20003",
        "age": 27,
        "sex": "男"
    },
    {
        "stu_id": "23100701",
        "stu_c": "231007",
        "stu_name": "紫薇格格",
        "addr": "湖南",
        "college": "湖南大学",
        "major": "材料物理",
        "starttime": "2016-09-01",
        "endtime": "2020-07-01",
        "edu": "本科",
        "cou_id": "20004",
        "age": 26,
        "sex": "女"
    },
    {
        "stu_id": "23100702",
        "stu_c": "231007",
        "stu_name": "小懂师兄",
        "addr": "湖南",
        "college": "广州大学",
        "major": "土木工程",
        "starttime": "2016-09-01",
        "endtime": "2020-07-01",
        "edu": "本科",
        "cou_id": "20005",
        "age": 26,
        "sex": "男"
    }
]


# 1. 查询所有学生信息
@app01.get("/students/", response_model=List[Student], summary="获取所有学生信息")
async def get_all_students():
    """返回系统中所有学生的完整信息列表"""
    return students


# 2. 通过学生编号查询某个学生
@app01.get("/students/id/{stu_id}", response_model=Student, summary="按ID查询学生")
async def get_student_by_id(stu_id: str):
    """根据学生ID查询特定学生的详细信息"""
    for student in students:
        if student["stu_id"] == stu_id:
            return student
    raise HTTPException(status_code=404, detail=f"学生ID {stu_id} 不存在")


# 3. 通过学生姓名查询学生（支持模糊查询）
@app01.get("/students/name/{stu_name}", response_model=List[Student], summary="按姓名查询学生")
async def get_students_by_name(stu_name: str):
    """根据学生姓名查询学生信息，支持模糊匹配"""
    matched_students = [s for s in students if stu_name in s["stu_name"]]
    if not matched_students:
        raise HTTPException(status_code=404, detail=f"未找到姓名包含 {stu_name} 的学生")
    return matched_students


# 4. 添加学生信息
@app01.post("/students/", response_model=Student, summary="添加新学生")
async def add_student(student: Student):
    """添加新学生信息，若学生ID已存在则返回错误"""
    # 检查学生ID是否已存在
    for existing in students:
        if existing["stu_id"] == student.stu_id:
            raise HTTPException(
                status_code=400,
                detail=f"学生ID {student.stu_id} 已存在"
            )
    students.append(student.dict())
    return student


# 5. 修改学生信息
@app01.put("/students/{stu_id}", response_model=Student, summary="更新学生信息")
async def update_student(stu_id: str, updated_student: Student):
    """根据学生ID更新学生信息"""
    for index, student in enumerate(students):
        if student["stu_id"] == stu_id:
            # 确保更新时ID保持一致
            if updated_student.stu_id != stu_id:
                raise HTTPException(
                    status_code=400,
                    detail="更新时学生ID不能修改"
                )
            students[index] = updated_student.dict()
            return students[index]
    raise HTTPException(status_code=404, detail=f"学生ID {stu_id} 不存在")


# 6. 通过学生ID删除学生
@app01.delete("/students/{stu_id}", summary="删除学生信息")
async def delete_student(stu_id: str):
    """根据学生ID删除对应的学生信息"""
    global students
    # 检查学生是否存在
    for student in students:
        if student["stu_id"] == stu_id:
            students = [s for s in students if s["stu_id"] != stu_id]
            return {"message": f"学生ID {stu_id} 已成功删除"}
    raise HTTPException(status_code=404, detail=f"学生ID {stu_id} 不存在")


if __name__ == '__main__':
    uvicorn.run('学生管理系统:app',host='localhost', port=8080, reload=True)